import React from 'react'
import {
    Form,
    Button,
    message,
    Icon,
    Input,
    Steps,
    Upload,
    Select,
    Cascader,
} from 'antd'
import { observer, inject } from 'mobx-react'
import _ from 'lodash'
import util from '../../../common/util'
import Tip from "../../common/tip"
import BraftEditor from 'braft-editor'
import 'braft-editor/dist/braft.css'

const FormItem = Form.Item


function beforeUpload(file) {
    const isJPG = file.type === 'image/jpeg'||file.type==='image/png';
    if (!isJPG) {
        message.error('只能上传就jpg和npg文件!');
    }
    const isLt2M = file.size / 1024 / 1024 < 3;
    if (!isLt2M) {
        message.error('图片大小不可超过3MB!');
    }
    return isJPG && isLt2M;
}

@inject("store")
@observer
class ExhibitorForm extends React.Component {
    constructor() {
        super()
    }
    upLoadImg = (e) => {
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    }
    componentDidMount() {
        let id=this.props.id
        if(id!=-1){
            this.props.store.actions.getExhibitorDetail(id);
        }
    }
    componentWillReceiveProps=(nextProps)=>{
        if(nextProps.id=="-1"&&!this.props.store.hasProps){
            setTimeout(()=>{
                this.props.store.actions.clearExhibitorDetail();
            },500)
        }
    }
    render() {
        let {store,form,id} = this.props
        let {current,actions,hasRe,exhibitorInfo}=store
        const Step = Steps.Step;
        const formItemLayout = {
            labelCol: { span: 4 },
            wrapperCol: { span: 16 },
        };
        const tailFormItemLayout = {
            wrapperCol: {
                sm: {
                    span: 8,
                    offset: 4,
                },
            },
        };
        const { getFieldDecorator } = this.props.form;
        const uploadButton = (
            <div>
                <Icon type={store.imgLoading ? 'loading' : 'plus'} />
                <div className="ant-upload-text">Upload</div>
            </div>
        );
        const uploadButton2 = (
            <div>
                <Icon type={store.imgLoading2 ? 'loading' : 'plus'} />
                <div className="ant-upload-text">Upload</div>
            </div>
        );
        const uploadFn = (param) => {
            const serverURL = '/api/common/upload'
            const xhr = new XMLHttpRequest
            const fd = new FormData()
            // libraryId可用于通过mediaLibrary示例来操作对应的媒体内容
            const successFn = (response) => {
                // 假设服务端直接返回文件上传后的地址
                // 上传成功后调用param.success并传入上传后的文件地址
                param.success({
                    url: JSON.parse(xhr.responseText).result.finalPath,
                })
            }
            const progressFn = (event) => {
                // 上传进度发生变化时调用param.progress
                param.progress(event.loaded / event.total * 100)
            }
            const errorFn = (response) => {
                // 上传发生错误时调用param.error
                param.error({
                    msg: 'unable to upload.'
                })
            }
            xhr.upload.addEventListener("progress", progressFn, false)
            xhr.addEventListener("load", successFn, false)
            xhr.addEventListener("error", errorFn, false)
            xhr.addEventListener("abort", errorFn, false)
            fd.append('file', param.file)
            xhr.open('POST', serverURL, true)
            xhr.send(fd)
        }
        const editorProps = {
            height: 300,
            contentFormat: 'html',
            media:{
                allowPasteImage: true, // 是否允许直接粘贴剪贴板图片（例如QQ截图等）到编辑器
                image: true, // 开启图片插入功能
                video:false, // 开启视频插入功能
                audio:false, // 开启音频插入功能
                validateFn: null, // 指定本地校验函数，说明见下文
                uploadFn: uploadFn, // 指定上传函数，说明见下文
                removeConfirmFn: null, // 指定删除前的确认函数，说明见下文
                onRemove: null, // 指定媒体库文件被删除时的回调，参数为被删除的媒体文件列表(数组)
                onChange: null, // 指定媒体库文件列表发生变化时的回调，参数为媒体库文件列表(数组)
                onInsert: null, // 指定从媒体库插入文件到编辑器时的回调，参数为被插入的媒体文件列表(数组)
            }
        }
        const step1=(
            <div>
                {
                    id==-1&&
                    <FormItem
                        {...formItemLayout}
                        label="邀请码"
                    >
                        {getFieldDecorator('code', {
                            validateTrigger: ['onChange', 'onBlur'],
                            rules: [{required: true, whitespace: true, message: '请输入邀请码!'},
                                {max: 15, message: '邀请码不得大于15位'},
                                {pattern: '^[A-Za-z0-9]+$', message: '邀请码只能由数字和字母组成'}],
                        })(
                            <Input placeholder="请输入邀请码"/>
                        )}
                    </FormItem>
                }
                <FormItem
                    {...tailFormItemLayout}
                >
                    <Button type="primary" onClick={() => actions.verifyCode(form)} style={{marginTop:'20px'}}>下一步</Button>
                </FormItem>
            </div>
        );
        const step2=(
            <div>
                {
                    id==-1&&
                    <FormItem
                        {...formItemLayout}
                        label="展览名称"
                    >
                        {getFieldDecorator('expoName', {
                            initialValue: store.expoName
                        })(
                            <Input disabled={true}/>
                        )}
                    </FormItem>
                }
                <FormItem
                    {...formItemLayout}
                    label="展商名称"
                >
                    {getFieldDecorator('companyName', {
                        initialValue:exhibitorInfo.companyName,
                        validateTrigger: ['onChange', 'onBlur'],
                        rules: [{ required: true, whitespace:true,message: '请输入展商名称!' },
                            {max:30,message:'展商名称不可大于30字'}],
                    })(
                        <Input placeholder="请输入展商名称"/>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="展商简称"
                >
                    {getFieldDecorator('companyAbbreviation', {
                        initialValue:exhibitorInfo.companyAbbreviation,
                        validateTrigger: ['onChange', 'onBlur'],
                        rules: [{ required: true,whitespace:true, message: '请输入展商简称!' },
                            {max:6,message:'简称不得大于6位'}],
                    })(
                        <Input placeholder="请输入展商简称"/>
                    )}
                </FormItem>
                {
                id==-1&&
                <FormItem
                    {...formItemLayout}
                    label="所在展位"
                    hasFeedback
                    validateStatus={hasRe == 1 ? "success" : hasRe == -1 || hasRe == -3 ? "error" : hasRe == -2 ? "validating" : null}
                    help={hasRe == 1 ? "展位可用" : hasRe == -1 ? "展位已被占用，请联系主办方" : hasRe == -3 ? "请选择展位！" : null}
                >
                    {getFieldDecorator('stand', {
                        rules: [{required: true, message: '请选择展位!'}],
                    })(
                        <Cascader
                            placeholder={'请选择展位'}
                            options={store.hallOptions}
                            loadData={actions.loadStand}
                            onChange={actions.standChange}
                        />
                    )}
                </FormItem>
                }
                <FormItem
                    {...formItemLayout}
                    label="参展商LOGO"
                >
                    {getFieldDecorator('companyImg', {
                        initialValue:exhibitorInfo.companyImg,
                        validateTrigger: ['onChange', 'onBlur'],
                        rules: [{ required: true, message: '请选择图片!' }],
                    },{
                        valuePropName: 'fileList',
                        getValueFromEvent:this.upLoadImg,
                    })(
                        <Upload
                            name="file"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            action="/api/common/upload"
                            beforeUpload={beforeUpload}
                            onChange={actions.handleImgChange}
                        >
                            {store.imageUrl ? <img src={store.imageUrl} alt="avatar" /> : uploadButton}
                        </Upload>
                    )}
                </FormItem>
                {
                    id==-1&&(
                        <FormItem
                            {...tailFormItemLayout}
                        >
                            <Button type="primary" onClick={() => actions.next(form)} style={{marginTop:'20px'}}>下一步</Button>
                        </FormItem>
                    )
                }
            </div>
        );
        const step3=(
            <div>
                <FormItem
                    {...formItemLayout}
                    label="公司地址"
                >
                    {getFieldDecorator('address', {
                        initialValue:exhibitorInfo.address,
                        validateTrigger: ['onChange', 'onBlur'],
                        rules: [{ required: true, message: '请输入公司地址!' },
                            {max:50,message:'公司地址不得大于50字'}],
                    })(
                        <Input placeholder="请输入公司地址"/>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="行业/服务领域"
                >
                    {getFieldDecorator('companyScope', {
                        initialValue:exhibitorInfo.companyScope,
                        validateTrigger: ['onChange', 'onBlur'],
                        rules: [{ required: true, message: '请输入服务领域!' },
                            {max:50,message:'服务领域不得大于50字'}],
                    })(
                        <Input placeholder="请输入服务领域"/>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="联系人"
                >
                    {getFieldDecorator('contacts', {
                        initialValue:exhibitorInfo.contacts,
                        validateTrigger: ['onChange', 'onBlur'],
                        rules: [{ required: true, message: '请输入联系人姓名!' },
                            {max:10,message:'联系人姓名不得多于10字'}],
                    })(
                        <Input placeholder="请输入联系人姓名"/>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="联系人电话"
                >
                    {getFieldDecorator('contactsPhone', {
                        initialValue:exhibitorInfo.contactsPhone,
                        validateTrigger: ['onChange', 'onBlur'],
                        rules: [{ required: true, message: '请输入联系人电话!' },
                            {pattern:'^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$',message:'请输入正确手机号'},
                            {max:16,message:'联系人电话不得大于16位'}],
                    })(
                        <Input placeholder="请输入联系人电话"/>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="联系人电子邮箱"
                >
                    {getFieldDecorator('contactsEmail', {
                        initialValue:exhibitorInfo.contactsEmail,
                        validateTrigger: ['onChange', 'onBlur'],
                        rules: [{ required: true, message: '请输入联系人电子邮箱!' },
                            {pattern:'^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$',message:'请输入正确邮箱'},
                            {max:20,message:'联系人电子邮箱不得大于20位'}],
                    })(
                        <Input placeholder="请输入联系人电子邮箱"/>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="公司介绍"
                >
                    <div style={{border:'1px #d9d9d9 solid',borderRadius:'4px'}}>
                        {getFieldDecorator('companyIntroduction', {
                            initialValue:exhibitorInfo.companyIntroduction,
                            rules: [{ required: true, message: '请输入公司介绍!' },
                                { max: 1000, message: '内容太长' }],
                        })(
                            <BraftEditor {...editorProps} initialContent={exhibitorInfo.companyIntroduction}/>
                        )}
                    </div>
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="产品服务介绍"
                >
                    <div style={{border:'1px #d9d9d9 solid',borderRadius:'4px'}}>
                        {getFieldDecorator('serviceIntroduction', {
                            initialValue:exhibitorInfo.serviceIntroduction,
                            rules: [{ required: true, message: '请输入产品服务介绍!' },
                                { max: 1000, message: '内容太长' }],
                        })(
                            <BraftEditor {...editorProps} initialContent={exhibitorInfo.serviceIntroduction}/>
                        )}
                    </div>
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="公司官网网址"
                >
                    {getFieldDecorator('officialUrl', {
                        initialValue:exhibitorInfo.officialUrl,
                        validateTrigger: ['onChange', 'onBlur'],
                        rules: [{max:30,message:'公司官网网址不得大于50位'}],
                    })(
                        <Input placeholder="请输入公司官网网址"/>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="公司传真"
                >
                    {getFieldDecorator('companyFax', {
                        initialValue:exhibitorInfo.companyFax,
                        validateTrigger: ['onChange', 'onBlur'],
                        rules: [{max:16,message:'公司传真不得大于16位'}],
                    })(
                        <Input placeholder="请输入公司传真"/>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="联系人QQ"
                >
                    {getFieldDecorator('qq', {
                        initialValue:exhibitorInfo.qq,
                        validateTrigger: ['onChange', 'onBlur'],
                        rules: [{pattern:'[1-9][0-9]{4,}',message:'请输入正确QQ号'},
                            {max:16,message:'联系人QQ不得大于16位'}],
                    })(
                        <Input placeholder="请输入联系人QQ"/>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="联系人微信"
                >
                    {getFieldDecorator('wechat', {
                        initialValue:exhibitorInfo.wechat,
                        validateTrigger: ['onChange', 'onBlur'],
                        rules: [{max:20,message:'联系人微信不得大于20位'}],
                    })(
                        <Input placeholder="请输入联系人微信"/>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="微信二维码"
                >
                    {getFieldDecorator('wechatQrcode', {

                    },{
                        valuePropName: 'fileList',
                        getValueFromEvent:this.upLoadImg,
                    })(
                        <Upload
                            name="file"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            action="/api/common/upload"
                            beforeUpload={beforeUpload}
                            onChange={actions.handleImgChange2}
                        >
                            {store.imageUrl2 ? <img src={store.imageUrl2} alt="avatar" /> : uploadButton2}
                        </Upload>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="案例介绍"
                >
                    <div style={{border:'1px #d9d9d9 solid',borderRadius:'4px'}}>
                        {getFieldDecorator('caseIntroduction', {
                            initialValue:exhibitorInfo.caseIntroduction,
                            rules: [{ max: 1000, message: '内容太长' }],
                        })(
                            <BraftEditor {...editorProps} initialContent={exhibitorInfo.caseIntroduction}/>
                        )}
                    </div>
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="人才招聘"
                >
                    <div style={{border:'1px #d9d9d9 solid',borderRadius:'4px'}}>
                        {getFieldDecorator('companyRecruit', {
                            initialValue:exhibitorInfo.companyRecruit,
                            rules: [{ max: 1000, message: '内容太长' }],
                        })(
                            <BraftEditor {...editorProps} initialContent={exhibitorInfo.companyRecruit}/>
                        )}
                    </div>
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="公司产品介绍"
                    extra="最多只能上传5个文件"
                >
                    {getFieldDecorator('participantFile', {

                    },{
                        valuePropName: 'fileList',
                        getValueFromEvent:this.upLoadImg,
                    })(
                        <Upload
                            name="file"
                            action="/api/common/upload"
                            defaultFileList={store.defaultFileList}
                            onChange={actions.getFileListLength}
                            disabled={store.fileListLength>4}
                        >
                            <Button>
                                <Icon type="upload" /> 点击上传
                            </Button>
                        </Upload>
                    )}
                </FormItem>
                {
                    id==-1&&(
                        <FormItem
                            {...tailFormItemLayout}
                        >
                            <Button onClick={() => actions.prev()} style={{marginRight:'10px',marginTop:'20px'}}>上一步</Button>
                            <Button type="primary" onClick={() => actions.finish(form)} style={{marginTop:'20px'}}>下一步</Button>
                        </FormItem>
                    )
                }
            </div>
        );
        const updateInfo=(
            <Form>
                {step2}
                {step3}
                <FormItem
                    {...tailFormItemLayout}
                >
                    <Button type="primary" onClick={()=>actions.updateInfo(form)}>立即修改</Button>
                </FormItem>
            </Form>
        );
        const step4=(
            <div style={{paddingLeft:'200px',paddingTop:'50px'}}>
                <h1 style={{fontSize:'28px'}}><Icon type="check-circle-o" className="icon-green"/> 恭喜你登录成功！</h1>
                <a href="javascript:" onClick={actions.resetCurrent}>再登录一个</a>
                {/*<a href={`/exhibition/exhibitor/?id=${store.id}`} target="_blank">快去看看自己的展位吧</a>*/}
            </div>
        );
        const steps = [{
            title: '邀请码',
        }, {
            title: '展位信息填写',
        }, {
            title: '公司信息填写',
        }, {
            title: '登录成功',
        }];
        const createInfo=(
            <Form>
                <Steps current={current} style={{marginBottom:'70px'}}>
                    {steps.map(item => <Step key={item.title} title={item.title} />)}
                </Steps>
                {
                    current ===0
                    &&
                    step1
                }
                {
                    current === 1
                    &&
                    step2
                }
                {
                    current ===2
                    &&
                    step3
                }
                {
                    current===3
                    &&
                    step4
                }
            </Form>
        );

        return (
            <div>
                {
                    id==-1&&<div><Tip title={'参展商登录'}/>{createInfo}</div>
                }
                {

                    id!=-1&&<div><Tip title={'参展商信息修改'}/>{updateInfo}</div>
                }
            </div>
        )
    }
}

const Exhibitor=Form.create()(ExhibitorForm);

export default Exhibitor
